import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { verifyToken } from '@/lib/auth';
import { cookies } from 'next/headers';
import { hashPassword } from '@/lib/auth';
import { comparePassword } from '@/lib/auth';

export async function PUT(request: NextRequest) {
  const token = cookies().get('token')?.value;
  if (!token) {
    console.log('PUT /api/profile: Missing token');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  let payload;
  try {
    payload = await verifyToken(token);
  } catch (error) {
    console.error('PUT /api/profile: Invalid token', error);
    return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
  }

  if (!payload) {
    console.log('PUT /api/profile: Invalid payload');
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { currentPassword, newPassword } = await request.json();

    // 验证输入
    if (!currentPassword || !newPassword) {
      return NextResponse.json(
        { error: '当前密码和新密码都是必填项' },
        { status: 400 }
      );
    }

    const user = await prisma.user.findUnique({
      where: { id: payload.user_id },
      select: { password: true }
    });

    if (!user || !user.password) {
      return NextResponse.json({ error: '未找到用户' }, { status: 404 });
    }

    const isPasswordValid = await comparePassword(currentPassword, user.password);
    if (!isPasswordValid) {
      return NextResponse.json({ error: '当前密码不正确' }, { status: 400 });
    }

    const hashedPassword = await hashPassword(newPassword);

    await prisma.user.update({
      where: { id: payload.user_id },
      data: { password: hashedPassword }
    });

    return NextResponse.json({ message: '密码更新成功' });
  } catch (error) {
    console.error('Password update error:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}
